/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FormMessageSender.java
 *
 * Created on Nov 22, 2010, 4:15:24 PM
 */
package com.perficient.ibuzz.ui;

import com.perficient.ibuzz.controller.IBuzzController;
import com.perficient.ibuzz.model.Message;
import com.perficient.ibuzz.validation.CharacterValidationResult;
import com.perficient.ibuzz.validation.CharacterValidator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

/**
 *
 * @author Trainning
 */
public class FormMessageSender extends javax.swing.JFrame {

    public static final String WINDOW_TITLE = "iBuzz Message Sender";
    public static final String BUTTON_SEND = "Button Send";
    public static final String BUTTON_CANCEL = "Button Cancel";
    public static final String LABEL_LIMIT = "Label Limit";
    public static final String TEXT_MESSAGE = "Text Message";
    public static final String LIST_MESSAGE = "List Message";

    private static final int DELAY = 2000;
    private static final CharacterValidator validator = new CharacterValidator();
    private IBuzzController controller = null;

    /** Creates new form FormMessageSender */
    public FormMessageSender(IBuzzController contr) {
        controller = contr;
        this.addWindowListener(new BuzzWindowAdapter(contr));
        initComponents();
        initNames();
        listMessage.setModel(new DefaultListModel());

        final FormMessageSender fms = this;
        ActionListener taskPerformer = new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
                    if(fms.isShowing()){
                        fms.setListMessage();
                        Logger.getLogger(IBuzzController.class.getName()).log(Level.INFO, "Refresh");
                    }
                   
              }
        };
        new javax.swing.Timer(DELAY, taskPerformer).start();
    }

    private void initNames() {
        this.setName(WINDOW_TITLE);
        btnCancel.setName(BUTTON_CANCEL);
        btnSend.setName(BUTTON_SEND);
        lblCharactersLeft.setName(LABEL_LIMIT);
        txtMessage.setName(TEXT_MESSAGE);
        listMessage.setName(LIST_MESSAGE);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtMessage = new javax.swing.JTextArea();
        btnSend = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        lblCharactersLeft = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        listMessage = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("iBuzz Message Sender");

        txtMessage.setColumns(20);
        txtMessage.setRows(5);
        txtMessage.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtMessageKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtMessageKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(txtMessage);

        btnSend.setText("Send");
        btnSend.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSendActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        lblCharactersLeft.setText("You have 140 characters left.");

        jScrollPane2.setViewportView(listMessage);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblCharactersLeft)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 105, Short.MAX_VALUE)
                        .addComponent(btnSend)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnCancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancel)
                    .addComponent(btnSend)
                    .addComponent(lblCharactersLeft))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        txtMessage.setText(null);
        setCharacterLimitationMsg(140);
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSendActionPerformed

        Message message = new Message();
        String filledInMessage = this.txtMessage.getText();
        if("".equals(filledInMessage.trim())) {
            return ;
        }
        message.setText(filledInMessage);
        message.setPostDate(new Date());
        controller.postMessage(message);
        this.txtMessage.setText("");
        setListMessage();
        setCharacterLimitationMsg(140);
    }//GEN-LAST:event_btnSendActionPerformed

    private void txtMessageKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMessageKeyTyped
        CharacterValidationResult result = validator.validate(txtMessage.getText());
        if (0 == result.getLeftCharNumber()) {
            evt.consume();
            setCharacterLimitationMsg(0);
        }
    }//GEN-LAST:event_txtMessageKeyTyped

    private void txtMessageKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMessageKeyReleased
        CharacterValidationResult result = validator.validate(txtMessage.getText());
        setCharacterLimitationMsg(result.getLeftCharNumber());
    }//GEN-LAST:event_txtMessageKeyReleased
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnSend;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblCharactersLeft;
    private javax.swing.JList listMessage;
    private javax.swing.JTextArea txtMessage;
    // End of variables declaration//GEN-END:variables

    public void setCharacterLimitationMsg(int count) {
        lblCharactersLeft.setText(String.format("You have %d characters left.", count));
    }

    public void setListMessage() {
        List<Message> list = controller.retrieveMessages();

        DefaultListModel listModel = new DefaultListModel();
        listMessage.setModel(listModel);

        for (int i = 0; i < list.size(); i++) {
            Message item = (Message)list.get(i);

            Date createDate = item.getPostDate();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String strCreateDateWithoutTime = df.format(createDate);
            String strRightNow = df.format(new Date());

            String format;
            if (strCreateDateWithoutTime.equals(strRightNow)) {
                format = "HH:mm";
            } else {
                format = "dd-MM HH:mm";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            String strCreateDate = sdf.format(createDate);
            int length = item.getAuthor().indexOf(" ");
            String author = item.getAuthor();
            if (length != -1) {
                author = author.substring(0, length);
            }
            String output = author + ": " + item.getText() + " @ "
                    + strCreateDate;
            listModel.addElement(output);

        }
        this.listMessage.updateUI();
    }
}
